<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}研发导出配置`"
    width="80%"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[80vh]">
      <!-- <VForm ref="form" :model="model" :fieldList="fieldList" :options="formOption" :rules="rules" :disabled="disabled">
      </VForm> -->
      <el-form ref="formRef" label-position="top" :model="form" :rules="rules">
        <el-row :gutter="21">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="conf_name">
              <el-input
                v-model="form.conf_name"
                placeholder="请输入配置名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属系统" prop="home_system">
              <el-select
                class="w-full"
                v-model="form.home_system"
                @change="changeSystem"
              >
                <el-option
                  v-for="item in options.home_system"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大导出数量" prop="export_maximum">
              <el-input
                v-model="form.export_maximum"
                placeholder="请输入最大导出数量"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导出枚举" prop="tag_id">
              <el-select
                class="w-full"
                v-model="form.tag_id"
                placeholder="请选择导出枚举"
                filterable
                clearable
              >
                <el-option
                  v-for="item in options.exportEnum"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每页请求数" prop="pagesize">
              <el-input
                v-model="form.pagesize"
                placeholder="请输入每页请求数"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件类型" prop="file_type">
              <el-radio-group v-model="form.file_type">
                <el-radio
                  :label="item.value"
                  v-for="(item, index) in options.file_type"
                  :key="index"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="接口地址" required>
              <template v-for="(item, index) in form?.api_urls" :key="index">
                <VGroup class="mt-[6px]">
                  <el-select v-model="item.request_type" class="w-full">
                    <el-option
                      v-for="it in options.api_request_type"
                      :key="it.value"
                      :label="it.label"
                      :value="it.value"
                    />
                  </el-select>
                  <el-input
                    class="w-full"
                    v-model="item.api"
                    placeholder="请输入接口地址"
                  ></el-input>
                  <div class="mx-[8px] w-[80px]">
                    <span
                      class="hover:text-[#2080f0] cursor-pointer"
                      @click.native="handleUrlAdd"
                      ><SvgIcon icon-class="Plus" class="text-[12px] inline"/>
                    </span>
                    <span
                      class="hover:text-[#2080f0] cursor-pointer ml-[8px]"
                      @click.native="handleUrlDelete(index)"
                      v-if="form.api_urls.length > 1"
                      ><SvgIcon icon-class="Minus" class="text-[12px] inline"/>
                    </span>
                  </div>
                </VGroup>
              </template>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="接口类型" prop="api_request_type">
              <el-select class="w-full" v-model="form.api_request_type">
                <el-option v-for="item in options.api_request_type" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div class="mb-[10px] flex items-center">
        <el-button type="primary" @click="handleAddRow">新增</el-button>
        <el-button type="primary" @click="handleTemplate">模板下载</el-button>
        <el-upload
          action
          class="importExcel"
          :auto-upload="false"
          accept=".xls,.xlsx"
          :show-file-list="false"
          @change="handleSelectFile"
        >
          <el-button type="primary" class="mx-[12px]">批量导入</el-button>
        </el-upload>
        <el-button type="primary" @click="handleDownFile">批量导出</el-button>
        <el-button type="danger" @click="handleBatchDelete">清空</el-button>
      </div>
      <div class="exportTable pb-[20px]">
        <vxe-table ref="tableRef" :data="tableData" max-height="400">
          <vxe-column title="" width="60">
            <template #default>
              <i class="diag_icon cursor-pointer hover:text-[#3487ff]">
                <svg-icon icon-class="menu" class="text-[16px]" />
              </i>
            </template>
          </vxe-column>
          <vxe-column type="seq" title="序号" width="60"></vxe-column>
          <vxe-column field="field_name" title="字段中文名*">
            <template #default="{ row }">
              <el-input v-model="row.field_name" />
            </template>
          </vxe-column>
          <vxe-column field="field_key" title="数据库字段*">
            <template #default="{ row }">
              <el-input v-model="row.field_key" />
            </template>
          </vxe-column>
          <vxe-column field="field_type" title="字段类型">
            <template #default="{ row }">
              <el-input v-model="row.field_type" />
            </template>
          </vxe-column>
          <vxe-column field="remark" title="备注">
            <template #default="{ row }">
              <el-input v-model="row.remark" />
            </template>
          </vxe-column>
          <vxe-column title="操作" width="50">
            <template #default="{ rowIndex }">
              <el-button type="danger" link @click="handleDelete(rowIndex)">
                删除
              </el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave(formRef)"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import * as XLSX from "xlsx";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElMessage, selectGroupKey } from "element-plus";
import Sortable from "sortablejs";
import VForm from "@/components/Form/index.vue";
import { exportConfigTemplate, getDropDown } from "../../api";
import {
  createExportConfig,
  updateExportConfig,
  exportConfigDetail,
} from "../../api";
import { ref, toRefs } from "vue";
import { overallOptions } from "@/api/public.js";
import { mapTableData } from "@/utils/tools.js";
const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
});

const tableRef = ref();
const tableData = ref([]);

const emit = defineEmits(["update:modelValue", "refresh", "close"]);

const formOption = {
  inline: true,
  labelPosition: "top",
};

const rules = {
  conf_name: [{ required: true, message: "请输入配置名称", trigger: "blur" }],
  home_system: [
    { required: true, message: "请选择所属系统", trigger: "change" },
  ],
  api_url: [{ required: true, message: "请输入接口地址", trigger: "blur" }],
  api_request_type: [
    { required: true, message: "请选择接口类型", trigger: "blur" },
  ],
  export_maximum: [
    { required: true, message: "请输入最大导出数量", trigger: "blur" },
  ],
  file_type: [{ required: true, message: "请选择文件类型", trigger: "blur" }],
};

// const form = ref()
const loading = ref();
const model = ref({ export_maximum: "1000" });
const exportEnum = ref([]);

const publicStyle = { style: { width: "408px" } };
const data = reactive({
  fieldList: [
    { field: "conf_name", label: "配置名称", ...publicStyle },
    {
      field: "home_system",
      origin: "home_system",
      label: "所属系统",
      type: "select",
      ...publicStyle,
    },
    { field: "api_url", label: "接口地址", ...publicStyle },
    {
      field: "api_url",
      label: "导出枚举",
      type: "select",
      options: {
        data: [
          {
            label: "2222",
            value: "2222",
          },
        ],
      },
      ...publicStyle,
    },
    {
      field: "api_request_type",
      label: "接口类型",
      origin: "api_request_type",
      type: "select",
      ...publicStyle,
    },
    {
      field: "export_maximum",
      label: "最大导出数量",
      type: "number",
      ...publicStyle,
    },
    { field: "pagesize", label: "每页请求数", type: "number", ...publicStyle },
    {
      field: "file_type",
      label: "文件类型",
      type: "radio",
      origin: "file_type",
      options: {
        data: [],
      },
      ...publicStyle,
    },
  ],
  form: { api_urls: [{ request_type: null, api: null, key: 1 }] },
  options: {},
});

const { fieldList, form, options } = toRefs(data);

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      nextTick(() => {
        rowDrop();
      });
    } else {
      model.value = { export_maximum: "1000" };
      tableData.value = [];
      // form.value?.resetForm()
    }
  },
  { immediate: true }
);

watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val);
      });
    }
  }
);

const readFile = (file) => {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (ev) => {
      resolve(ev.target.result);
    };
  });
};

const handleSelectFile = async (e) => {
  let file = e.raw;
  if (file.name.indexOf("xlsx") === -1 || file.name.indexOf("xls") === -1) {
    ElMessage.warning("请选择xlsx、xls格式文件");
    return;
  }
  if (!file) {
    ElMessage.warning("文件导入失败");
    return;
  }
  let data = await readFile(file);
  let workbook = XLSX.read(data, { type: "binary" });
  let worksheet = workbook.Sheets[workbook.SheetNames[0]];
  let result = XLSX.utils.sheet_to_json(worksheet);
  if (result && result.length) {
    for (const n of result) {
      tableData.value.push({
        field_name: n["字段中文名"] || "",
        field_key: n["数据库字段"] || "",
        field_type: n["字段类型"] || "",
        remark: n["备注"] || "",
      });
    }
  }
};

const rowDrop = () => {
  const tbody = document.querySelector(
    ".exportTable .vxe-table--body-wrapper tbody"
  );
  new Sortable(tbody, {
    handle: ".diag_icon",
    animation: 180,
    delay: 0,
    onEnd: ({ newIndex, oldIndex }) => {
      if (newIndex === oldIndex) {
        return false;
      }
      const rows = JSON.parse(JSON.stringify(tableData.value));
      const currRow = rows.splice(oldIndex, 1)[0];
      rows.splice(newIndex, 0, currRow);
      tableData.value = [];
      nextTick(() => {
        tableData.value = rows;
      });
    },
  });
};

const handleDelete = (index) => {
  tableData.value.splice(index, 1);
};
const handleBatchDelete = () => {
  tableData.value = [];
};
const handleDownFile = () => {
  if (!tableData.value.length) return ElMessage.warning("无数据导出!");
  const tHeader = ["字段中文名", "数据库字段", "字段类型", "备注"];
  const filterVal = ["field_name", "field_key", "field_type", "remark"];
  const data = mapTableData(tableData.value, tHeader, filterVal);
  // 创建工作簿和工作表
  const worksheet = XLSX.utils.json_to_sheet(data);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // 导出为Excel文件
  const timestamp = new Date().getTime();
  XLSX.writeFile(workbook, `字段导出_${timestamp}.xlsx`);
};
const handleTemplate = async () => {
  const { data } = await exportConfigTemplate();
  console.warn(data);
  if (data?.url) {
    window.open(data.url, "noopener", "noreferrer");
  }
};

const getDetail = async (id) => {
  try {
    const { data = {} } = await exportConfigDetail({ id });
    const { export_field = [], ...reset } = data;
    changeSystem(data.home_system);
    form.value = data;
    tableData.value = export_field;
  } catch (e) {
    tableData.value = [];
    console.error(e);
  }
};

const handleAddRow = async () => {
  tableData.value.push({});
  await nextTick();
  tableRef.value?.loadData(tableData.value).then(() => {
    const el = tableRef.value.$el.querySelector(".vxe-table--body-wrapper");
    if (el) {
      el.scrollTop = el.scrollHeight;
    }
  });
};

const isEdit = computed(() => {
  return !!props.id;
});

const formRef = ref(null);
const handleSave = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.value?.api_urls?.length) {
          const _emptyApi = form.value?.api_urls.findIndex(
            (n) => !n.request_type || !n.api
          );
          if (_emptyApi > -1) {
            ElMessage.warning(`请补充第${_emptyApi + 1}个接口地址!`);
            return;
          }
        } else {
          ElMessage.warning(`请添加接口地址`);
          return;
        }
        loading.value = true;
        const tableDataAll = tableRef.value.getTableData()?.fullData;
        const formInfo = await form.value;

        if (!tableDataAll?.length) {
          ElMessage.warning(`请先添加字段`);
          return;
        }
        const _emptyFieldName = tableDataAll.findIndex(
          (n) => !n.field_name || !n.field_name?.toString().trim()?.length
        );
        if (_emptyFieldName > -1) {
          ElMessage.warning(`请补充第${_emptyFieldName + 1}个字段中文名!`);
          return;
        }
        const _emptyFieldKey = tableDataAll.findIndex(
          (n) => !n.field_key || !n.field_key?.toString().trim()?.length
        );
        if (_emptyFieldKey > -1) {
          ElMessage.warning(`请补充第${_emptyFieldKey + 1}个数据库字段名称!`);
          return;
        }
        const api = {
          edit: updateExportConfig,
          add: createExportConfig,
        };
        const { id } = props;
        await api[isEdit.value ? "edit" : "add"]({
          id: id || undefined,
          ...formInfo,
          export_field: tableDataAll,
        });
        ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
        handleClose(true);
      } catch (e) {
        if (e.toString().includes(false)) {
          ElMessage.warning("请检查表单信息");
        }
        console.error(e);
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleClose = (refresh) => {
  emit("update:modelValue", false);
  emit("close");
  formRef.value.resetFields();
  form.value.api_urls = [{ key: +new Date(), request_type: null, api: null }];
  if (refresh) emit("refresh");
};

const getOverallOptions = async () => {
  try {
    const res = await overallOptions();
    options.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};
getOverallOptions();

const changeSystem = async (val) => {
  form.value.tag_id = "";
  getDropDownList(val);
};
const getDropDownList = async (home_system) => {
  try {
    const res = await getDropDown({
      home_system,
    });
    options.value.exportEnum = res.data;
  } catch (e) {
    throw Error(e);
  }
};

const handleUrlAdd = () => {
  form.value.api_urls.push({ key: +new Date(), request_type: null, api: null });
};
const handleUrlDelete = (index) => {
  form.value.api_urls.splice(index, 1);
};
</script>
